package cn.autumnorange.authorization.security.security;

import org.springframework.web.context.WebApplicationContext;

import javax.servlet.ServletContext;


public class JsApiTicketThread implements Runnable {

    private WebApplicationContext webApplicationContext;

    public JsApiTicketThread(WebApplicationContext webApplicationContext) {
        this.webApplicationContext = webApplicationContext;
    }

    @Override
    public void run() {
        while (true) {
            try {
                ServletContext servletContext = webApplicationContext.getServletContext();
                String access_token = (String) servletContext.getAttribute("access_token");

                JsApiTicket jsApiTicket = null;

                if (null != access_token && !"".equals(access_token)) {

                    jsApiTicket = CommonUtil.getJsApiTicket(access_token);

                    if (null != jsApiTicket) {
                        servletContext.setAttribute("jsapi_ticket", jsApiTicket.getTicket());

                        Thread.sleep((jsApiTicket.getExpiresIn() - 200) * 1000);
                    }
                }
                Thread.sleep(60 * 1000);
            } catch (Exception e) {
                try {
                    Thread.sleep(60 * 1000);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                e.printStackTrace();
            }
        }
    }

}
